import json
from socket import timeout
from urllib.request import build_opener
from urllib import error


def get_ip_address(request):
    return request.META['HTTP_X_FORWARDED_FOR'] if 'HTTP_X_FORWARDED_FOR' in request.META else request.META[
        'REMOTE_ADDR']


def get_ip_info(ip):
    api_url_taobao = 'http://ip.taobao.com/service/getIpInfo.php?ip='
    headers = ('User-Agent', 'Mozilla/5.0 (Windows NT 5.1; rv:14.0) Gecko/20100101 Firefox/14.0.1')
    opener = build_opener()
    opener.addheaders = [headers]
    try:
        data = opener.open(api_url_taobao + ip, timeout=1).read()
    except (error.URLError, timeout):
        data = {'country': '火星', 'region': '火星', 'city': '火星'}
    else:
        data = data.decode('UTF-8')
        data = json.loads(data)['data']

    try:
        if data['country'] == '未分配或者内网IP':
            data['country'] = data['region'] = data['city'] = '火星'
    except TypeError:
        data = {'country': '火星', 'region': '火星', 'city': '火星'}

    return {'country': data['country'], 'region': data['region'], 'city': data['city']}


def ip_protect(ip):
    first = ip.index('.')
    last = ip.rindex('.')
    return ip[:first] + '.*.*.' + ip[last + 1:]
